package pub.cleangao.codegen.literal;

import lombok.extern.slf4j.Slf4j;
import pub.cleangao.codegen.GenConfigHolder;
import pub.cleangao.codegen.enquiry.EnquiryServiceFactory;
import pub.cleangao.codegen.enquiry.TableEnquiry;
import pub.cleangao.codegen.enquiry.TableInfo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;


/**
 * 输出代码文本文件
 */
@Slf4j
public class CodeOutput {

    public static void generateCodeLiteral(String rootPath, boolean singlePot) {
        GenConfigHolder config = new GenConfigHolder(rootPath);
        TableEnquiry tableEnquiry = EnquiryServiceFactory.getTableEnquiry(config);
        List<TableInfo> tableInfos = tableEnquiry.getTableInfos();
        // 1. 过滤表
        List<String> excludeTables = new ArrayList<>();
        List<String> includeTables = new ArrayList<>();
        if (config.getTableExclude() != null && !config.getTableExclude().isEmpty()) {
            String[] tablesExclude = config.getTableExclude().split(",");
            for (String table : tablesExclude) {
                if (table == null || table.trim().isEmpty()) {
                    continue;
                }
                excludeTables.add(table.trim());
            }
        }
        if (config.getTableInclude() != null
                && !config.getTableInclude().isEmpty()
                && !"*".equals(config.getTableInclude().trim())) {
            String[] tablesInclude = config.getTableInclude().split(",");
            for (String table : tablesInclude) {
                if (table == null || table.trim().isEmpty()) {
                    continue;
                }
                includeTables.add(table.trim());
            }
        }
        if (includeTables.size() == 0 && "*".equals(config.getTableInclude().trim())) {
            // 在全部表中剔除
            if (excludeTables.size() > 0) {
                Iterator<TableInfo> itr = tableInfos.listIterator();
                while (itr.hasNext()) {
                    TableInfo tableInfo = itr.next();
                    if (excludeTables.contains(tableInfo.getTableName())) {
                        itr.remove();
                    }
                }
            }
        } else {
            // 在include表中剔除
            Iterator<String> itr = includeTables.listIterator();
            while (itr.hasNext()) {
                String include = itr.next();
                if (excludeTables.contains(include)) {
                    itr.remove();
                }
            }
            if (includeTables.size() == 0) {
                return;
            }
            Iterator<TableInfo> tableInfoIterator = tableInfos.listIterator();
            while (tableInfoIterator.hasNext()) {
                TableInfo tableInfo = tableInfoIterator.next();
                if (!includeTables.contains(tableInfo.getTableName())) {
                    tableInfoIterator.remove();
                }
            }
        }
        // 2. 修改表名前缀和后缀
        String discardPrefix = config.getDiscardPrefix();
        String discardSuffix = config.getDiscardSuffix();
        if (discardPrefix != null && !discardPrefix.isEmpty()) {
            for (TableInfo tableInfo : tableInfos) {
                if (isAllChar(discardPrefix, '?') || isAllChar(discardPrefix, '0')) {
                    tableInfo.setTableName(tableInfo.getTableName().substring(discardPrefix.length()));
                } else {
                    tableInfo.setTableName(tableInfo.getTableName().replaceFirst(discardPrefix, ""));
                }
            }
        }
        if (discardSuffix != null && !discardSuffix.isEmpty()) {
            for (TableInfo tableInfo : tableInfos) {
                if (isAllChar(discardSuffix, '?') || isAllChar(discardSuffix, '0')) {
                    tableInfo.setTableName(tableInfo.getTableName().substring(0, tableInfo.getTableName().length() - discardPrefix.length()));
                } else {
                    if (tableInfo.getTableName().lastIndexOf(discardSuffix) > 0) {
                        tableInfo.setTableName(tableInfo.getTableName().substring(0, tableInfo.getTableName().length() - discardPrefix.length()));
                    }
                }
            }
        }
        log.info("include tables: {}", includeTables);
        log.info("exclude tables: {}", excludeTables);
        log.info("discard prefix: {}", discardPrefix);
        log.info("discard suffix: {}", discardSuffix);
        config.setSinglePot(singlePot);
        // 生成service文件
        for (TableInfo tableInfo : tableInfos) {
            TemplateBuilder.assembleServiceLiteral(tableInfo, config);
        }
        List<String> processing = Stream.of(config.getGenerateFolder().split(",")).map(String::toUpperCase).toList();
        if (!singlePot && processing.contains("API")) {
            //  生成其他文件(api-stub)
            for (TableInfo tableInfo : tableInfos) {
                TemplateBuilder.assembleStubLiteral(tableInfo, config);
            }
        }
        // 通用代码
        if (processing.contains("CONFIG")) {
            CommonsBuilder.buildServiceCommons(config);
            if (!singlePot && processing.contains("API")) {
                // stub 的通用代码
                CommonsBuilder.buildStubCommons(config);
            }
        }
    }

    private static boolean isAllChar(String str, char _a) {
        String b = str.replace(String.valueOf(_a), "");
        return b.length() == 0;
    }


}
